package com.wangzhen.abstractroutingdatasource.asecpt;

import com.wangzhen.abstractroutingdatasource.annotation.ReadOnly;
import com.wangzhen.abstractroutingdatasource.config.DataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * 写一个切面来切换数据使用哪种数据源，重写 getOrder 保证本切面优先级高于事务切面优先级
 */
@Aspect
@Component
public class ReadOnlyInterceptor implements Ordered {

    private final Logger logger = LoggerFactory.getLogger(ReadOnlyInterceptor.class);

    @Around("@annotation(readOnly)")
    public Object setRead(ProceedingJoinPoint joinPoint, ReadOnly readOnly) throws Throwable{
        try{
            DataSourceContextHolder.setDataSOurceType(DataSourceContextHolder.READ);
            return joinPoint.proceed();
        }finally {
            //清除 dataSourceType 一方面为了避免内存泄漏，更重要的是避免对后续在本线程上执行的操作产生影响
            DataSourceContextHolder.clearDataSourceType();
            logger.info("清除threadLocal");
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

